<template>
  <div>
    <div class="table-page-search-wrapper">
      <el-card>
        <el-form inline :model="queryParams" @submit.native.prevent>
          <el-row :gutter="48">
            <!-- 搜索item项 -->
            <el-col :md="8" :sm="24">
              <el-form-item label="机构名称" prop="keyword">
                <el-input
                  v-model.trim="queryParams.keyword"
                  placeholder="请输入机构名称查询"
                  clearable
                  @keyup.enter.native="handleSearch"
                />
              </el-form-item>
            </el-col>
            <!-- 查询按钮 -->
            <el-col :md="16" :sm="24">
              <el-form-item>
                <span
                  class="table-page-search-submitButtons"
                >
                  <el-button type="primary" @click="handleSearch">查 询</el-button>
                  <el-button style="margin-left: 8px" @click="resetQuery">重 置</el-button>
                </span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <div class="table-block">
      <el-card>
        <div slot="header" class="clearfix">
          <!-- 左侧修改新增按钮组 -->
          <div class="left">
            <el-button type="primary" @click="handleAdd('add',null)" v-if="menuButtonPermissions.includes('organization.add')">新 增</el-button>
            <el-button type="primary" v-else style="visibility: hidden;">新 增</el-button>
          </div>
          <!-- 右侧按钮组 -->
          <div class="right">
            <div class="table-operator card-right">
            </div>
          </div>
        </div>
        <!-- 表格数据列表 -->
        <el-table
          :data="tableList"
          row-key="id"
          ref="tableRef"
          stripe
          :height="tableMaxHeigth"
          lazy
          :load="load"
          :tree-props="{children: 'subRes', hasChildren: 'hasChildren'}">
          <el-table-column prop="name" label="机构名称" show-overflow-tooltip/>
          <el-table-column prop="shortName" label="机构简称" width="200px" align="center" show-overflow-tooltip/>
          <el-table-column
            prop="orgFormName"
            label="组织形式"
            width="200px"
            align="center"
            center
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ $dictTranslation(scope.row.orgForm+'', getOrgFormListData) }}
            </template>
          </el-table-column>
          <el-table-column prop="state" label="机构状态" align="center" show-overflow-tooltip width="200" >
            <template slot-scope="scope">
              <el-switch
                class="switch"
                :active-value="1"
                :inactive-value="2"
                v-model="scope.row.state"
                :disabled="!menuButtonPermissions.includes('organization.upd')"
                @change="stateChange(scope.row)"
                active-text="正常"
                inactive-text="禁用">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="机构同步状态" align="center" show-overflow-tooltip width="200" >
            <template slot-scope="scope">
              <el-switch
                class="switch"
                :active-value="true"
                :inactive-value="false"
                :disabled="!menuButtonPermissions.includes('organization.upd')"
                v-model="scope.row.ifSync"
                @change="ifSyncChange(scope.row)"
                active-text="同步"
                inactive-text="不同步">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="category"
            label="来源方式"
            width="100"
            align="center"
            center
            show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.category === 1 ? '内部' : '外部' }}</template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="100" v-if="menuButtonPermissions.includes('organization.add') || menuButtonPermissions.includes('organization.upd') || menuButtonPermissions.includes('organization.deleted')">
            <template #default="{ row }">
              <el-button
                type="text"
                icon="el-icon-plus"
                class="table-button-size"
                v-if="menuButtonPermissions.includes('organization.add')"
                title="新增下级"
                @click="handleAdd('addNext',row)"></el-button>
              <el-button
                type="text"
                icon="el-icon-edit"
                class="table-button-size"
                v-if="menuButtonPermissions.includes('organization.upd')"
                title="编辑"
                @click="handleAdd('update',row)"></el-button>
              <el-button
                type="text"
                icon="el-icon-delete"
                class="table-button-size"
                v-if="menuButtonPermissions.includes('organization.deleted')"
                title="删除"
                @click="handleDelete(row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <edit ref="editRef" :getOrgFormListData="getOrgFormListData" @getTableList="getTableList" :tableList="tableList"></edit>
    </div>
  </div>
</template>

<script>
import { organizationTree } from '@/api/userManage'
import actions from '@/cros/actions'

import { orgDeleted, updState, updSync, dictData } from '@/api/orgManage'
import edit from './edit.vue'
export default {
  name: 'OrgManage',
  components: {
    edit
  },
  data () {
    return {
      tableMaxHeigth: 0,
      tableList: [],
      // 查询参数
      queryParams: {
        parent: '',
        keyword: ''
      },
      getOrgFormListData: [],
      menuButtonPermissions: [],
      maps: new Map() // 用于存储 子节点懒加载的数据
    }
  },
  mounted () {
    this.getOrgFormList()
    actions.onGlobalStateChange((state, prevState) => {
      this.menuButtonPermissions = state.menuButtonPermissions.map(v => v.buttonKey)
    }, true)
    this.getTableList('')
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.setTableHeight)
    // 初始化表格高度
    this.setTableHeight()
  },
  methods: {
    async getOrgFormList () {
      const res = await dictData({
        dictType: 'org_form',
        pageNo: 1,
        pageSize: 9999,
        searchType: 'project'
      })
      this.getOrgFormListData = res.data.list
    },
    stateChange (row) {
         updState({ id: row.id, state: row.state }).then((res) => {
           if (res.code === 'success') {
            this.$message.success('操作成功')
           } else {
            row.state = row.state === 1 ? 2 : 1
            this.$message.error(res.msg)
          }
         })
    },
    ifSyncChange (row) {
      updSync({ id: row.id, ifSync: row.ifSync }).then((res) => {
           if (res.code === 'success') {
            this.$message.success('操作成功')
           } else {
            row.state = !row.state
            this.$message.error(res.msg)
          }
         })
    },
    handleDelete (row) {
       this.$confirm(`是否删除名称为 '${row.name}' 的组织机构?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
       }).then(() => {
         orgDeleted({ id: row.id }).then((res) => {
           if (res.code === 'success') {
            this.$message.success('操作成功')
            this.$set(this.$refs.tableRef.store.states, 'lazyTreeNodeMap', {})
            this.$set(this.$refs.tableRef.store.states, 'treeData', {})
            this.getTableList()
           } else {
            this.$message.error(res.msg)
          }
         })
        }).catch(() => {
          console.log('取消删除')
        })
    },
    // 新增 / 编辑
    handleAdd (str, row) {
      this.$refs.editRef.open(str, JSON.parse(JSON.stringify(row)))
    },
    beforeDestroy () {
    // 组件销毁前移除事件监听
    window.removeEventListener('resize', this.setTableHeight)
    },
    setTableHeight () {
      this.$nextTick(() => {
        this.tableMaxHeigth = document.body.offsetHeight - 230
      })
    },
    async load (tree, treeNode, resolve) {
      this.maps.set(tree.id, { tree, treeNode, resolve })
      const query = JSON.parse(JSON.stringify(this.queryParams))
      query.parent = tree.id
      const res = await organizationTree(query)
      if (res.code !== 'success') return
      console.log(res.data, 'res.data')
        res.data.forEach(v => {
        this.$set(v, 'hasChildren', v.childNum > 0)
        if (v.ifSync === null) {
          v.ifSync = true
        }
      })
      resolve(res.data)
    },
    handleSearch () {
      this.getTableList()
    },
    // 获取列表数据
    async getTableList () {
      const res = await organizationTree(this.queryParams)
      this.tableList = []
      this.$nextTick(() => {
        if (res.code !== 'success') return
      res.data.forEach(v => {
        this.$set(v, 'hasChildren', v.childNum > 0)
        if (v.ifSync === null) {
          v.ifSync = true
        }
      })
      console.log(res.data, 'res.data')
        this.tableList = res.data
      })
    },
    // 重置
    resetQuery () {
      this.queryParams.keyword = ''
      this.getTableList()
    }
  }
}
</script>
<style scoped lang="scss">
</style>
